package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleClient;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.*;

@Service
public class AuditServiceImpl implements IAuditService {

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private GreenImageScan imageScan;

    @Autowired
    private IWmNewsService newsService;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private ArticleClient articleClient;

    @Autowired
    private IWmUserService userService;

    @Autowired
    private IWmChannelService channelService;

    @Autowired
    private IWmSensitiveService sensitiveService;
    //文章审核
    @Override
    @Async
    public void audit(WmNews wmNews) {

        //提取自媒体文章中的文本内容和图片
        Map<String,Object> contentMap=getTextAndImageFromContent(wmNews.getContent());
        //文本内容
        String text = (String) contentMap.get("text");
        //图片
        List<String> images = (List<String>) contentMap.get("image");
        //封面图片
        List<ImageDto> imageDtos = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        for (ImageDto imageDto : imageDtos) {
            if (imageDto!=null&&!StringUtils.isEmpty(imageDto.getUrl())){
                if (!images.contains(imageDto.getUrl())){
                    images.add(imageDto.getUrl());
                }
            }
        }
        // 先进行自管理敏感词的审核
        boolean wordResult = checkWord(text, wmNews);
        if (!wordResult) return;
        //调用阿里云文本审核
        boolean textResult=checkText(text,wmNews);
        if (!textResult) return;
        // 文本审核通过后,调用阿里云图片审核
        boolean imageResult=checkImage(images,wmNews);
        if (!imageResult) return;
        //图片审核通过后，发布自媒体文章到APP库
        publishArticle(wmNews);
    }
    //自管理敏感词审核
    private boolean checkWord(String text, WmNews wmNews) {
        boolean result = false;
        String content = wmNews.getTitle() + wmNews.getLabels() + text;
        // 判断是否已经存在敏感词数据
        if (SensitiveWordUtil.dictionaryMap.size() == 0) {
            // 从数据库查询所有敏感词
            LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
            // select sensitives from wm_sensitive
            query.select(WmSensitive::getSensitives);
            List<String> words = sensitiveService.listObjs(query, x -> x.toString());
            // 如果不存在,初始化map
            SensitiveWordUtil.initMap(words);
        }
        // 调用工具类的方法判断结果
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() == 0) {
            result = true;
        } else {
            // 修改自媒体文章状态为2,并且记录失败原因
            wmNews.setStatus(2);
            Set<String> keySet = map.keySet();
            String label = String.join(",", keySet);
            wmNews.setReason("自管理敏感词审核失败: " + label);
            newsService.updateById(wmNews);
        }
        return result;

    }

    //发布自媒体文章到APP库
    private void publishArticle(WmNews wmNews) {
        //远程调用文章微服务保存文章
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setId(null);
        //从自媒体用户表中查询文章作者id
        WmUser user = userService.getById(wmNews.getUserId());
        dto.setAuthorId(user.getApAuthorId());
        dto.setAuthorName(user.getName());
        //查询频道信息
        WmChannel channel = channelService.getById(wmNews.getChannelId());
        dto.setChannelName(channel.getName());
        dto.setLayout(wmNews.getType());
        dto.setFlag(0);
        //解析封面图片
        List<ImageDto> imageDtos = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        List<String> images=new ArrayList<>();
        for (ImageDto imageDto : imageDtos) {
            if (imageDto!=null&&!StringUtils.isEmpty(imageDto.getUrl())){
                if (!images.contains(imageDto.getUrl())){
                    images.add(imageDto.getUrl());
                }
            }
        }
        //前端显示的图片直接通过逗号隔开
        String join = String.join(",", images);
        dto.setImages(join);
        ResponseResult<Long> result = articleClient.saveArticle(dto);
        //判断结果
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            Long articleId = result.getData();
            if (articleId!=null){
                wmNews.setArticleId(articleId);
                wmNews.setStatus(9);
                newsService.updateById(wmNews);
            }
        }


    }

    //阿里云图片审核
    private boolean checkImage(List<String> images, WmNews wmNews) {
        if (images.size()==0){
            return true;
        }
        boolean result =false;
        //定义需要审核的图片字节数组集合
        List<byte[]>imageList=new ArrayList<>();
        try {

            // 如果MinIO是有公网IP的话,可以直接传URL地址给阿里云审核
            // 目前我们的MinIO是部署在内网,所以需要先下载图片,然后上传到阿里云审核
            // 遍历图片集合
            for (String image : images) {
                //下载图片
                InputStream inputStream = minIOService.download(image);
                //输入流转换为字节数组
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }
            Map map = imageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            //判断结果
            switch (suggestion){
                case "pass":
                    result=true;
                    break;
                case "block":
                    //修改自媒体文章状态为2，并且记录失败原因
                    wmNews.setType(2);
                    String label=(String) map.get("label");
                    wmNews.setReason("阿里云图片审核失败"+label);
                    newsService.updateById(wmNews);
                    break;

                case "review":
                    //修改自媒体文章状态为3
                    wmNews.setType(3);
                    newsService.updateById(wmNews);
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //调用阿里云文本审核
    private boolean checkText(String text, WmNews wmNews) {
        boolean result =false;
        // 审核内容包含标题+标签+内容中的文本
        String content= wmNews.getTitle()+wmNews.getLabels()+ text;
        try {
            Map map = textScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            //判断结果
            switch (suggestion){
                case "pass":
                    result=true;
                    break;
                case "block":
                    //修改自媒体文章状态为2，并且记录失败原因
                    wmNews.setType(2);
                    String label=(String) map.get("label");
                    wmNews.setReason("阿里云文本审核失败"+label);
                    newsService.updateById(wmNews);
                    break;

                case "review":
                    //修改自媒体文章状态为3
                    wmNews.setType(3);
                    newsService.updateById(wmNews);
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //获取文章中的内容和图片
    private Map<String, Object> getTextAndImageFromContent(String content) {
        Map<String,Object> map=new HashMap<>();
        //定义文本内容
        StringBuilder builder = new StringBuilder();
        //定义图片内容
        List<String> images=new ArrayList<>();
        //将content转换成对象集合
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        //遍历
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")){
                //文字内容
                builder.append(contentDto.getValue());
            }else {
                //图片
                images.add(contentDto.getValue());
            }
        }
        map.put("text",builder.toString());
        map.put("image",images);
        return map;
    }
}
